package com.etoak.filter;

import cn.hutool.json.JSONUtil;
import com.etoak.common.core.enums.ResultEnum;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.jwt.JwtUtil;
import com.etoak.properties.ImageProperties;
import com.etoak.properties.WhiteProperties;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenFilter implements GlobalFilter, Ordered { // 定义了一个类TokenFilter，它实现了GlobalFilter和Ordered接口

    @Autowired // 自动注入WhiteProperties类
    private WhiteProperties whiteProperties;

    @Autowired // 自动注入ImageProperties类
    private ImageProperties imageProperties;

    @Override // 重写GlobalFilter接口的filter方法
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求的uri
        String uri = request.getPath().value();
        // 如果uri在白名单中或者以图片服务的前缀开始，则放行请求
        if (whiteProperties.getList().contains(uri) || uri.startsWith(imageProperties.getPrefix())){
            return chain.filter(exchange); // 放行请求
        }
        // 获取请求头中的Authorization字段，即jwt token
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        // 如果token为空，则返回提示
        if (StringUtils.isEmpty(token)){
            return noAuto(exchange, ResultEnum.TOKEN_NOT_FOUND_ERROR);
        }
        // 尝试解析token，如果token过期，则捕获异常并返回提示
        try{
            JwtUtil.parse(token);
        }catch (ExpiredJwtException e){
            return noAuto(exchange, ResultEnum.TOKEN_TIMEOUT_EROOR);
        }catch (Exception e){ // 如果解析token出现其他异常，则返回提示
            return noAuto(exchange, ResultEnum.TOKEN_ERROR);
        }
        // 如果token校验通过，则放行请求
        return chain.filter(exchange);
    }

    private Mono<Void> noAuto(ServerWebExchange exchange, ResultEnum resultEnum){
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应头内容类型为json
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE,"application/json;charset=utf-8");
        // 创建失败结果的ResultVO对象
        ResultVO<Object> resultVO = ResultVO.failed(resultEnum);
        // 将结果对象转换为json字符串并包装成DataBuffer
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSONUtil.toJsonStr(resultVO).getBytes());
        // 将DataBuffer写入响应体
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override // 重写Ordered接口的getOrder方法，定义过滤器执行的顺序
    public int getOrder() {
        return -100; // 数字越小，优先级越高
    }
}
